package com.mjgy.repository;

import java.util.List;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;

import com.mjgy.entity.MessageEntity;

/**
* @Description: 消息中心持久类
* @author quanlq
* @date 2018年9月1日
* @version V1.0
*/
public interface MessageRepository extends JpaRepository<MessageEntity, Long>, JpaSpecificationExecutor<MessageEntity> {

	List<MessageEntity> findByUserId(Long userId);
	
	Integer countByUserIdAndIsChecked(Long userId, int isChecked);

	Integer countByUserIdAndTypeAndIsChecked(Long userId, String type, int isChecked);
	
	MessageEntity findTopByUserIdAndTypeOrderBySendTimeDesc(Long userId, String type);
	
	@SuppressWarnings("rawtypes")
	@Query(value = "select msg.id, "
			+ "msg.user_id, "
			+ "msg.type, "
			+ "msg.sender_id, "
			+ "msg.content, "
			+ "msg.send_time, "
			+ "msg.is_checked, "
			+ "msg.is_allowed, "
			+ "msg.send_image, "
			+ "msg.is_burned, "
			+ "usr.nickname, "
			+ "usr.avatar "
			+ "from e_message msg "
			+ "left join e_user usr on msg.sender_id = usr.id "
			+ "where msg.user_id = :userId and msg.type = :type "
			+ "order by msg.send_time desc "
			+ "limit :page, :size", nativeQuery = true)
	List findByUserIdAndType(@Param("userId") Long userId, @Param("type") String type, @Param("page") Integer page, 
			@Param("size") Integer size);
	
	@Modifying
	@Query("update MessageEntity set isChecked = 1 where userId = :userId and type = :type")
	void updateIsCheckedByUserIdAndType(@Param("userId") Long userId, @Param("type") String type);
	
	@Modifying
	@Query("update MessageEntity set isAllowed = :isAllowed where id = :id")
	void updateIsAllowedById(@Param("isAllowed") Integer isAllowed, @Param("id") Long id);
	
	@Modifying
	@Query("update MessageEntity set isBurned = 1 where id = :id")
	void updateIsBurnedById(@Param("id") Long id);
	
}

